package com.until;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class MakeParameters {

    private static final String ENCODING = "UTF-8";
    private static final String APIURL = "https://api.chinac.com/";
    //预定义编码时间格式
    public static String formatIso8601Date(){
        TimeZone timeZone = TimeZone.getTimeZone("PRC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
        df.setTimeZone(timeZone);
        String nowAsISO = df.format(new Date());
        return nowAsISO;
    }

    public static Map parameters(){
        Map parameters = new HashMap();
        parameters.put("Region","cn-guangzhou1");
        parameters.put("AccessKeyId","24e4f96b014446a980bb4b457f5c8f9b");
        parameters.put("Date",formatIso8601Date());
        parameters.put("Action","DescribeImages");
        parameters.put("Version","1.0");
        return parameters;
    }

    public static StringBuilder urlEncode(Map parameters) throws Exception{
        //排序请求参数
        String[] sortedKeys = (String[]) parameters.keySet().toArray(new String[]{});
        //对请求参数进行URL编码
        StringBuilder canonicalizedQueryString = new StringBuilder();
        for (String key :sortedKeys){
            canonicalizedQueryString.append("&").append(percent_encode(key)).append("=").append((percent_encode(parameters.get(key).toString())));
        }
        return canonicalizedQueryString;
    }

    public static String makeSignature(Map<String,String> parameters) throws Exception{
        StringBuilder canonicalizedQueryString = urlEncode(parameters);
        String url = canonicalizedQueryString.toString().substring(1);
        //对进行过编码的字符串进行MD5加密
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(url.getBytes());
        byte b[] = md.digest();
        int i ;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0;offset<b.length;offset++){
            i = b[offset];
            if (i<0)
                i += 256;
            if (i<16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        String md5 = buf.toString();
        String accessKeySecret = "9f6b4885f9824fda83184f808880a8d7";
        final String SEPARATOR = "\n";
        final String HTTP_METHOD = "GET";
        final String CONTEXTTYPE = "application/json;charset=UTF-8";
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(HTTP_METHOD).append(SEPARATOR);//method
        stringToSign.append(md5).append(SEPARATOR);//md5加密的请求参数
        stringToSign.append(CONTEXTTYPE).append(SEPARATOR);//contextType
        stringToSign.append(percent_encode( parameters.get("Date"))).append(SEPARATOR);//Date
        String signature = sign_string(stringToSign.toString(),accessKeySecret);
        System.out.println(signature);
        signature =percent_encode(signature);
        parameters.put("Signature",signature);
        String urlName = canonicalizedQueryString.toString();
        urlName = urlName+"&Signature"+"="+signature;
        urlName = urlName.substring(1);
        urlName = APIURL+ "?" +urlName;
        System.out.println("urlName:"+urlName);
        return urlName;
    }

    public static String sign_string(String string,String accessKeySecret) throws Exception{
    final String ALGORITHM = "HmacSHA256";
    final String ENCODING = "UTF-8";
    Mac mac = Mac.getInstance(ALGORITHM);
    mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING),ALGORITHM));
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] signData = mac.doFinal(string.getBytes());
    String signature = new String(Base64.encodeBase64(signData));
    return signature;
}


    public static String percent_encode(String str)throws UnsupportedEncodingException{
//        编码时空格要转换成 “%20” , 而不是 “+”；"*"要转换成"%2A"
       String string = str !=null ? URLEncoder.encode(str,ENCODING).replace("+","%20".replace("*","%2A".replace("%7E","~"))):null;
       return string;
    }

    public static void main(String[] args) throws Exception{
    }


}
